package com.example.rdcproject.ving.notes.view.Admin;

import com.example.rdcproject.ving.notes.dao.WordBookDao;
import com.example.rdcproject.ving.notes.service.ConnectionPool;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;


public class WordBookView extends JFrame{

    private JTextField bookNameField;
     private JButton searchButton ;
    private JButton editButton ;

    // 创建表格模型
    DefaultTableModel model = new DefaultTableModel();
        private final JTable table = new JTable(model);


    private Connection connection;
        private Statement statement;
        private ResultSet resultSet;



        public  WordBookView() {
            WordBookDao wordBookDao = new WordBookDao();
            // 初始化各个组件
            JLabel bookNameLabel = new JLabel("书名：");
            bookNameField = new JTextField();
            searchButton = new JButton("搜索");
            JButton addButton = new JButton("添加");
            editButton = new JButton("修改");
            JButton deleteButton = new JButton("删除");


            // 设置组件大小、位置等
            bookNameLabel.setBounds(20, 20, 40, 30);
            bookNameField.setBounds(70, 20, 200, 30);
            searchButton.setBounds(280, 20, 80, 30);
            addButton.setBounds(20, 60, 80, 30);
            editButton.setBounds(120, 60, 80, 30);
            deleteButton.setBounds(220, 60, 80, 30);


            // 设置窗口大小、可见性、关闭方式等
            setTitle("词书管理");
            setLayout(new FlowLayout());
            setSize(400, 350);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);

            JPanel mainPanel = new JPanel();
            setContentPane(mainPanel);
            //setContentPane(scrollPane);
            pack();

            mainPanel.setLayout(null);



            ConnectionPool connectionPool = null;
            // 连接数据库
            try {
                connectionPool = ConnectionPool.getInstance();
                connection = connectionPool.getConnection();
                statement = connection.createStatement();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 查询按钮
            searchButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String bookName = bookNameField.getText();
                    String word = JOptionPane.showInputDialog("请输入要查询的单词");
                    wordBookDao.searchWord(bookName,word);
                        }
            });

            // 添加按钮
            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String word = JOptionPane.showInputDialog("请输入要添加的单词");
                    String meaning = JOptionPane.showInputDialog("请输入你要添加的单词意思");
                    if (word != null && !word.equals("")) {
                        try {
                            // 向单词表中插入新单词
                            String sql = "insert into " + bookNameField.getText() + " (word,meaning) VALUES (?,?)";
                            PreparedStatement statement = connection.prepareStatement(sql);

                            statement.setString(1, word);
                            statement.setString(2, meaning);
                            statement.executeUpdate();


                            // 更新 TableModel
                            resultSet = statement.executeQuery("select * from " + bookNameField.getText());
                            // 将ResultSet转换为TableModel
                            DefaultTableModel model = new DefaultTableModel();
                            ResultSetMetaData rsmd = resultSet.getMetaData();
                            int columnCount = rsmd.getColumnCount();
                            for (int i = 1; i <= columnCount; i++) {
                                model.addColumn(rsmd.getColumnName(i));
                            }
                            while (resultSet.next()) {
                                Object[] row = new Object[columnCount];
                                for (int i = 1; i <= columnCount; i++) {
                                    row[i - 1] = resultSet.getObject(i);
                                }
                                model.addRow(row);
                            }
                             refreshTable();
                            // 设置JTable的数据模型
                            table.setModel(model);

                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                }
            });

            // 编辑按钮
            editButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String word = JOptionPane.showInputDialog("请输入要修改的单词");
                    String meaning = JOptionPane.showInputDialog("请输入你要修改的单词意思");

                        if (word != null && !word.equals("")) {
                            try {
                                wordBookDao.updateWord(bookNameField.getText(),word,meaning);
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                        }else {
                            JOptionPane.showMessageDialog(null,"修改失败");
                        }

                }
            });

            // 删除按钮
            deleteButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String word2 = JOptionPane.showInputDialog("请输入要删除的单词");
                         boolean result = wordBookDao.deleteWord(bookNameField.getText(),word2);
                            if (result ==true) {
                                JOptionPane.showMessageDialog(null, "删除成功！");
                            } else {
                                JOptionPane.showMessageDialog(null, "删除失败！");
                            }
                    }

            });

            //添加组件
            mainPanel.add(bookNameLabel);
            mainPanel.add(bookNameField);
            mainPanel.add(searchButton);
            mainPanel.add(addButton);
            mainPanel.add(editButton);
            mainPanel.add(deleteButton);
            JScrollPane scrollPane = new JScrollPane(table);
            mainPanel.add(scrollPane);



            setVisible(true);
        }
    public void refreshTable() throws SQLException {
        ConnectionPool connectionPool = null;
        try {
            connectionPool = ConnectionPool.getInstance();
            connection = connectionPool.getConnection();
            statement = connection.createStatement();


            String sql = "SELECT * FROM " + bookNameField.getText();
            ResultSet rs = statement.executeQuery(sql);
            // 更新表格数据
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            while (rs.next()) {
                Object[] rowData = new Object[2];
                rowData[0] = rs.getString("word");
                rowData[1] = rs.getString("meaning");
                model.addRow(rowData);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            assert connectionPool != null;
            connectionPool.releaseConnection(connection);

        }

    }






}
